<template>
  <div class="body">
    <div class="ser_div">
      <el-row>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 供货单位 </el-col>
            <el-col :span="16">
              <el-select v-model="ser.supplier_id" filterable placeholder="请选择供货单位" style="width: 100%">
                <el-option v-for="(item, index) in SupplierList" :key="index" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8"> 入库类别 </el-col>
            <el-col :span="16">
              <el-select v-model="ser.customer_id" filterable placeholder="请选择入库类别" style="width: 100%">
                <el-option label="入库单" value="1"> </el-option>
                <el-option label="出库单" value="2"> </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 订单日期范围 </el-col>
            <el-col :span="16">
              <el-date-picker v-model="order_data" @change="order_data_change" value-format="yyyy-MM-dd"
                type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
          </el-row>
        </el-col>
        <el-col>
          <el-button class="add_btn" @click="ser_warehouse">搜索</el-button>

          <el-button class="add_btn" @click="reset">重置</el-button>
          <el-button class="add_btn" @click="add_warehouse">新增出/入库单</el-button>
        </el-col>
        <el-col>
          <el-row style="display: flex; align-items: center">
            <el-col :span="8" style="text-align: center"> 当页总金额 </el-col>
            <el-col :span="16">
              <span style="font-size: 26px;color: #dc1111;font-weight: bold;"> {{ maony.toFixed(2) }}</span>
            </el-col>
          </el-row>

        </el-col>
      </el-row>
    </div>

    <el-table :data="productList" v-horizontal-scroll="'always'" v-loading="loading" border>
      <el-table-column prop="type" label="类型">
        <template slot-scope="scope">
          <span>{{ scope.row.type == 1 ? '入库单' : scope.row.type == 2 ? '出库单' : '半成品领料单' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="supply_order_number" label="单号"> </el-table-column>
      <el-table-column prop="stock" label="用料明细" min-width="400">
        <template slot-scope="scope">
          <table style="border-collapse: collapse" cellspacing="0" class="table_material">
            <tr>
              <th>材料名称</th>
              <th>数量</th>
              <th>单价</th>
              <th>金额</th>

            </tr>
            <tr v-for="(item, index) in scope.row.child" :key="index">
              <td>{{ item.material.name }} </td>
              <td>{{ item.num }} </td>
              <td>{{ item.unit_price }} </td>
              <td>{{ item.money }} </td>
            </tr>
          </table>
          <!-- <div v-for="(item, index) in scope.row.child" :key="index" style="display:grid;grid-template-columns: 1fr 1fr 1fr;">
                <span>名称：{{ item.material.name }} </span>
                <span>数量：{{ item.num }} </span>
                <span>单价:{{item.unit_price}}</span>
              </div> -->
        </template>
      </el-table-column>
      <!-- <el-table-column prop="num" label="数量"> </el-table-column> -->
      <el-table-column prop="money" label="金额"> </el-table-column>
      <el-table-column prop="clearing_form" label="结算方式">
        <template slot-scope="scope">
          <span v-if="scope.row.clearing_form == 1">赊账</span>
          <span v-if="scope.row.clearing_form == 2">线下</span>
          <span v-if="scope.row.clearing_form == 3">线上</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="300"> </el-table-column>
      <el-table-column prop="warehouse_id" label="库房">
        <template slot-scope="scope">
          {{ scope.row.warehouse && scope.row.warehouse.warehouse_name }}
        </template>
      </el-table-column>
      <el-table-column prop="after_num" label="加工后数量" width="200"> </el-table-column>
      <el-table-column prop="loss_num" label="损耗" width="200"> </el-table-column>
      <el-table-column label="供应商" width="200">
        <template slot-scope="scope">
          {{ scope.row.supplier && scope.row.supplier.name }}
        </template>
      </el-table-column>
      <el-table-column prop="buyer" label="采购人" width="200"> </el-table-column>
      <el-table-column prop="warehouse_keeper" label="仓库管理员" width="200"> </el-table-column>
      <el-table-column prop="finance" label="财务" width="200"> </el-table-column>
      <el-table-column prop="prepared_by" label="制单人" width="200"> </el-table-column>
      <el-table-column prop="warehouse_entry_time" width="200" label="入库时间"> </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <!--     <el-button
            v-if="scope.row.type==1"
            @click="clickBtn(1,scope.row)"
            type="text"
            >加工后数量</el-button>
          <el-button
            v-if="scope.row.type==1"
            @click="clickBtn(2,scope.row)"
            type="text"
            >损耗</el-button> -->
          <!-- <el-button
            @click="add_warehouse(scope.row)"
            type="text"
            icon="el-icon-edit"
            >编辑</el-button
          > -->
          <el-button @click="set_remark(scope.row)" type="text" icon="el-icon-edit">改备注</el-button>
          <!-- <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="是否删除这条数据？"
            @confirm="del_product(scope.row)"
          >
            <el-button slot="reference" type="text" icon="el-icon-delete">
              删除</el-button
            > -->
          <!-- </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background @prev-click="prev"
        @next-click="next" :current-page.sync="pagination.page" :page-size="pagination.per_page"
        layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="isProduct" width="50%" :close-on-click-modal="false" @close="close_dialog">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
        <el-row>
          <el-col :span="11">
            <el-form-item label="制单类别" prop="type">
              <el-select v-model="ruleForm.type" filterable placeholder="请选择制单类别" style="width: 100%"
                @change="changetype">
                <el-option label="入库单" value="1"> </el-option>
                <el-option label="出库单" value="2"> </el-option>
                <el-option label="半成品领料单" value="3"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-show="ruleForm.type != 3">
            <el-form-item label="材料列表">
              <el-select ref="select" filterable multiple v-model="child" placeholder="请选择材料" style="width: 100%"
                @change="child_change">
                <el-option v-for="item in materialList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-show="ruleForm.type == 3">
            <el-form-item label="半成品材料列表">
              <el-select filterable v-model="child" placeholder="请选择材料" style="width: 100%" @change="one_change">
                <el-option v-for="item in materialList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="材料信息" prop="child">
              <el-table :data="ruleForm.child" v-if="ruleForm.type != 3">
                <el-table-column v-for="(item, index) in col" :key="`col_${index}`" :prop="item.prop"
                  :label="item.label">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row['name']" :disabled="item.prop == 'name'"
                      v-if="item.prop == 'name' && index == 0"></el-input>
                    <el-input type="number" v-model="scope.row['num']" v-if="item.prop == 'num' && index == 1" @input="
                      num_change(scope.row['num'], scope.row['material_id'])
                      "></el-input>
                    <el-input type="number" v-model="scope.row['unit_price']"
                      :disabled="item.prop == 'unit_price' && ruleForm.type != 1"
                      v-if="item.prop == 'unit_price' && index == 2 && ruleForm.type != 3" @input="
                        num_change(scope.row['num'], scope.row['material_id'])
                        "></el-input>
                    <el-input type="number" v-model="scope.row['money']"
                      :value="scope.row['unit_price'] * scope.row['num']" :disabled="item.prop == 'money'"
                      v-if="item.prop == 'money' && index == 3 && ruleForm.type != 3"></el-input>
                    <el-input v-model="scope.row['remark']" v-if="item.prop == 'remark'"></el-input>
                  </template>
                </el-table-column>
              </el-table>
              <el-table :data="ruleForm.child" v-if="ruleForm.type == 3">
                <el-table-column prop="label" label="类别" width="200"> </el-table-column>
                <el-table-column prop="name" label="材料名称" width="200"> </el-table-column>
                <el-table-column prop="warehouse_keeper" label="数量" width="200">
                  <template slot-scope="scope">
                    <el-input type="number" v-model="scope.row.num"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="warehouse_keeper" label="备注" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="ruleForm.type != 3">
          <el-row>
            <el-col :span="11">
              <el-form-item label="供应商" prop="supplier_id">
                <el-select v-model="ruleForm.supplier_id" filterable placeholder="请选择供货单位" style="width: 100%">
                  <el-option v-for="item in SupplierList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="结算方式" prop="clearing_form">
                <el-select v-model="ruleForm.clearing_form" filterable placeholder="请选择入库类别" style="width: 100%">
                  <el-option label="赊账" value="1"> </el-option>
                  <el-option label="线下" value="2"> </el-option>
                  <el-option label="线上" value="3"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="库房" prop="warehouse_id">
                <el-select filterable v-model="ruleForm.warehouse_id" placeholder="请选择库房" style="width: 100%">
                  <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="供应单号" prop="supply_order_number">
                <el-input v-model="ruleForm.supply_order_number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="采购人" prop="buyer">
                <el-select filterable v-model="ruleForm.buyer" placeholder="请选择采购人" style="width: 100%">
                  <el-option v-for="item in user_List" :key="item.id"
                    :label="item.company_name + '(' + item.role[0].name + ')'" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="仓库管理员" prop="warehouse_keeper">
                <el-select v-model="ruleForm.warehouse_keeper" placeholder="请选择仓库管理员" style="width: 100%">
                  <el-option v-for="item in user_List" :key="item.id"
                    :label="item.company_name + '(' + item.role[0].name + ')'" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="财务人员" prop="finance">
                <el-select filterable v-model="ruleForm.finance" placeholder="请选择财务人员" style="width: 100%">
                  <el-option v-for="item in user_List" :key="item.id"
                    :label="item.company_name + '(' + item.role[0].name + ')'" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="制单人" prop="prepared_by">
                <el-select filterable v-model="ruleForm.prepared_by" placeholder="请选择制单人" style="width: 100%">
                  <el-option v-for="item in user_List" :key="item.id"
                    :label="item.company_name + '(' + item.role[0].name + ')'" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="11">
              <el-form-item label="入库时间" prop="warehouse_entry_time">
                <el-date-picker v-model="ruleForm.warehouse_entry_time" type="date" format="yyyy 年 MM 月 dd 日"
                  style="width: 100%" value-format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="ruleForm.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close_dialog">取 消</el-button>
        <el-button type="primary" @click="addhuojia('ruleForm')">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="modelText" :visible.sync="isShow" width="30%" :before-close="handleClose">
      <el-input v-model="num"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="financebtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="备注" :visible.sync="ispush_remark" width="30%" :before-close="handleClose_zd">
      <el-input v-model="remark"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose_zd">取 消</el-button>
        <el-button type="primary" @click="push_remark">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getWarehouseOrderList,
  getSupplierList,
  getMaterialList,
  getWarehouseList,
  createWarehouseOrder,
  updateWarehouseOrder,
  getSelfProductList,
  selfMaterialInfo,
} from "@/api/product/index";
import { getUserList } from "@/api/role/index";
export default {
  data() {
    return {
      order_data:[],
      maony: 0,
      ispush_remark: false,
      loading: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      ser: {
        supplier_id: "",
        customer_id: "",
        start_time:"",
        end_time:"",
      },
      TypeList: [],
      title: "",
      isProduct: false,
      productList: [],
      pagination: {
        per_page: 10,
        page: 1,
      },
      total: 0,
      ruleForm: {
        id: "",
        supplier_id: "",
        clearing_form: "",
        warehouse_id: "",
        buyer: "",
        supply_order_number: "",
        warehouse_keeper: "",
        finance: "",
        prepared_by: "",
        warehouse_entry_time: "",
        remark: "",
        type: "1",
        child: [],
      },
      rules: {
        // supplier_id: [
        //   { required: true, message: "请选择供应商", trigger: "blur" },
        // ],
        // clearing_form: [
        //   { required: true, message: "请选择结算方式", trigger: "blur" },
        // ],
        // warehouse_id: [
        //   { required: true, message: "请选择库房", trigger: "blur" },
        // ],
        // buyer: [{ required: true, message: "请选择采购人", trigger: "blur" }],
        // supply_order_number: [
        //   { required: true, message: "请输入供应单号", trigger: "blur" },
        // ],
        // warehouse_keeper: [
        //   { required: true, message: "请选择仓库管理员", trigger: "blur" },
        // ],
        // finance: [{ required: true, message: "请选择财务", trigger: "blur" }],
        // prepared_by: [
        //   { required: true, message: "请选择制单人", trigger: "blur" },
        // ],
        // warehouse_entry_time: [
        //   { required: true, message: "请选择入库时间", trigger: "blur" },
        // ],
        type: [{ required: true, message: "请选择制单类型", trigger: "blur" }],
        child: [{ required: true, message: "请选择供材料", trigger: "blur" }],
      },
      SupplierList: [],
      materialList: [],
      warehouseList: [],
      user_List: [],
      isShow: false,
      num: 0,
      modelText: "",
      col: [
        { label: "材料名称", prop: "name" },
        { label: "数量", prop: "num" },
        { label: "单价", prop: "unit_price" },
        { label: "金额", prop: "money" },
        { label: "备注", prop: "remark" },
        // { label: "ss", prop: "material_id" },
      ],
      child: [],
      self_product_id: "",
      row_id: "",
      remark: ""
    };
  },
  mounted() {
    this.getlist();
    this.get_SupplierList();
    this.get_MaterialList();
    this.get_WarehouseList();
    this.get_UserList();
  },
  methods: {
    order_data_change(val) {
      this.ser.start_time = val[0];
      this.ser.end_time = val[1];
    },
    set_remark(row) {
      this.row_id = row.id
      this.remark = row.remark
      this.ispush_remark = true
    },
    push_remark() {
      let data = {
        id: this.row_id,
        remark: this.remark
      }
      updateWarehouseOrder(data).then(res => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "更新成功",
          });
          this.handleClose_zd()
          this.getlist();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      })
    },
    handleClose_zd() {
      this.remark = ''
      this.row_id = ''
      this.ispush_remark = false
    },
    ser_warehouse() {
      this.maony=0
      this.pagination.per_page = 99
      this.getlist();
    },
    reset() {
      this.pagination.page = 1
      this.ser = {
        supplier_id: "",
        customer_id: "",
        start_time:"",
        end_time:"",
      }
      this.getlist();
    },
    changetype(e) {
      if (e) {
        this.$refs.select.query = ""
      }
      this.self_product_id = ""
      this.ruleForm.child = []
      this.child = []
      this.materialList = []
      if (e == 3) {
        getSelfProductList({ page: 1, per_page: 9999 }).then((res) => {
          if (res.code == 200) {
            this.materialList = res.data.data;
          }
        });
        this.col = [
          { label: "材料名称", prop: "name" },
          { label: "数量", prop: "num" },
          { label: "备注", prop: "remark" },
        ]
      } else {
        this.get_MaterialList();
        this.col = [
          { label: "材料名称", prop: "name" },
          { label: "数量", prop: "num" },
          { label: "单价", prop: "unit_price" },
          { label: "金额", prop: "money" },
          { label: "备注", prop: "remark" },
          // { label: "ss", prop: "material_id" },
        ]
      }
    },
    clickBtn(val, row) {
      this.row = row
      this.modelText = val == 1 ? "加工后数量" : "损耗"
      this.isShow = true
    },
    handleClose() {
      this.isShow = false;
      this.num = 0
    },
    financebtn() {
      let data = {
        id: this.row.id
      }
      if (this.modelText == "加工后数量") {
        data.after_num = this.num
      } else {
        data.loss_num = this.num
      }
      updateWarehouseOrder(data).then(res => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "更新成功",
          });
          this.getlist();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      })
      this.handleClose()
    },
    get_UserList() {
      getUserList().then((res) => {
        if (res.code == 200) {
          this.user_List = res.data.data;
        }
      });
    },
    // 仓库
    get_WarehouseList() {
      getWarehouseList().then((res) => {
        if (res.code == 200) {
          this.warehouseList = res.data.data;
        }
      });
    },
    // 金额计算
    num_change(val, id) {
      this.ruleForm.child.forEach((item) => {
        if (item.material_id == id) {
          item.money = item.num * item.unit_price;
        }
      });
      console.log(val, id);
    },
    // 单选
    one_change(val) {
      this.self_product_id = val
      selfMaterialInfo({ self_product_id: val }).then(res => {
        if (res.code == 200) {
          let data = []
          res.data.forEach(li => {
            data.push({
              material_id: li.id,
              label: li.label,
              name: li.name,
              num: 0,
              remark: ""
            })
          })
          this.ruleForm.child = data;
        }
      })
    },
    // 多选材料
    child_change(val) {
      console.log(val);
      let material_List = [];
      let materialList = this.materialList;
      for (let i = 0; i < val.length; i++) {
        materialList.forEach((item) => {
          if (item.id == val[i]) {
            let obj = {
              name: item.name,
              model_number: item.model_number,
              material_id: item.id,
              num: "",
              unit_price: item.w_price,
              money: "",
              remark: "",
            };
            material_List.push(obj);
          }
        });
      }
      this.ruleForm.child = material_List;
      console.log(this.ruleForm.child);
    },
    // 材料列表
    get_MaterialList() {
      getMaterialList().then((res) => {
        if (res.code == 200) {
          this.materialList = res.data;
          // console.log(this.materialList);
        }
      });
    },
    //供货单位
    get_SupplierList() {
      getSupplierList().then((res) => {
        if (res.code == 200) {
          this.SupplierList = res.data;
        }
      });
    },
    del_product(row) {
      delMaterial({ id: row.id, is_del: 1 }).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.getlist();
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
    close_dialog() {
      this.isProduct = false;
      this.ruleForm = {
        id: "",
        supplier_id: "",
        clearing_form: "",
        warehouse_id: "",
        buyer: "",
        supply_order_number: "",
        warehouse_keeper: "",
        finance: "",
        prepared_by: "",
        warehouse_entry_time: "",
        remark: "",
        type: "1",
        child: [],
      }
      this.child = []

    },
    addhuojia(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            ...this.ruleForm
          }
          if (data.type == 3) {
            data.self_product_id = this.self_product_id
          }
          createWarehouseOrder(data).then((res) => {
            if (res.code == 200) {
              this.isProduct = false;
              this.$message.success("提交成功");
              this.getlist();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    add_warehouse(row) {
      if (row.id) {
        this.ruleForm = row;
        this.title = "编辑出入库单";
      } else {
        this.title = "新增出入库单";
      }
      console.log(this, "this")
      this.isProduct = true;
      this.changetype();
    },
    getlist() {
      getWarehouseOrderList({ ...this.pagination, ...this.ser }).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
          this.productList.forEach(item => {
            this.maony += Number(item.money
            )
          })
          this.loading = false;
        }
      });
    },
    handleSizeChange(val) {
      console.log(val);
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagination.page = val;
      this.getlist();
    },
    prev() {
      this.pagination.page = this.pagination.page - 1;
      this.getlist();
    },
    next() {
      console.log("ss");
      this.pagination.page = this.pagination.page + 1;
      this.getlist();
    },
    changeValue(e) {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped>
.table_material {
  width: 100%;
}

.table_material tr th {
  border: 1px solid #000000;
  text-align: center;
}

.table_material tr td {
  border: 1px solid #000000;
  text-align: center;

}
</style>
